package com.china08.yxyapi.api.temp;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.huodong.lecture.YxyHuodongResResultSchool;
import com.china08.yxyapi.entity.db.huodong.lecture.YxyHuodongResResultTea;
import com.china08.yxyapi.entity.db.huodong.lecture.YxyHuodongResTemp;
import com.china08.yxyapi.repository.db.lectureresult.YxyHuodongResResultSchoolRepository;
import com.china08.yxyapi.repository.db.lectureresult.YxyHuodongResResultTeaRepository;
import com.china08.yxyapi.repository.db.lectureresult.YxyHuodongResTempRepository;

import io.swagger.annotations.Api;

@Api(tags = { "V01", "test" })
@CrossOrigin
@RestController
public class ResResultController extends YxyApiBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResResultController.class);

    @Autowired
    private JdbcTemplate template;

    @Autowired
    private YxyHuodongResResultTeaRepository teaRepository;

    @Autowired
    private YxyHuodongResTempRepository tempRepository;

    @Autowired
    private YxyHuodongResResultSchoolRepository schoolRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${yx.rest.api.yx.path}")
    private String baseUrl;

    @ResponseBody
    @RequestMapping(value = "/api_yw/temp/res/test", method = RequestMethod.GET)
    public String process() {
        task();

        return "ok";
    }

    private void task() {
        String sql = "SELECT city_code AS ccode,district_code AS dcode, province_code AS pcode,uploader_school_id AS sid,uploader_school_name AS sname,uploader_id AS uid, uploader_name AS uname,type_id AS tp,COUNT(1) AS c FROM yxy_res.yxy_res_resource WHERE  DATE(upload_time) >= '2017-11-15' AND DATE(upload_time) <= '2017-12-31' AND STATUS=1 AND view_scope=2 AND district_code = '610203' GROUP BY uploader_school_id,uploader_id,type_id";

        List<Map<String, Object>> forList2 = template.queryForList(sql);

        String sid = null;
        String uid = null;
        String type = null;
        YxyHuodongResTemp temp = null;
        tempRepository.deleteByAreaIdDistrict("610203");
        teaRepository.deleteByAreaIdDistrict("610203");
        schoolRepository.deleteByAreaIdDistrict("610203");
        List<YxyHuodongResTemp> list = new ArrayList<YxyHuodongResTemp>();
        for (Map<String, Object> map : forList2) {
            sid = (String) map.get("sid");
            if (StringUtils.isNoneBlank(sid)) {
                uid = (String) map.get("uid");
                if (StringUtils.isNoneBlank(uid)) {
                    type = (String) map.get("tp");
                    temp = new YxyHuodongResTemp();
                    temp.setSchoolId(sid);
                    temp.setTeaId(uid);
                    temp.setSchoolNick((String) map.get("sname"));
                    temp.setTeaName((String) map.get("uname"));
                    temp.setType(type);
                    temp.setAreaIdCity(map.get("ccode") != null ? map.get("ccode").toString() : "");
                    temp.setAreaIdDistrict(map.get("dcode") != null ? map.get("dcode").toString() : "");
                    temp.setAreaIdProvince(map.get("pcode") != null ? map.get("pcode").toString() : "");
                    temp.setCount(Integer.valueOf(map.get("c").toString()));
                    list.add(temp);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            List<YxyHuodongResTemp> listsave = tempRepository.save(list);
            LOGGER.info("保存成功temp：" + listsave.size());
        }
        try {
            Thread.sleep(5000); // 1000 毫秒，也就是1秒.
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        String sql1 = "SELECT school_id AS sid,tea_id AS tid FROM yxy_huodong.yxy_huodong_res_temp WHERE area_id_district='610203' GROUP BY school_id,tea_id";
        List<Map<String, Object>> forList3 = template.queryForList(sql1);
        List<YxyHuodongResTemp> list2 = null;
        List<YxyHuodongResResultTea> list3 = new ArrayList<YxyHuodongResResultTea>();
        for (Map<String, Object> map : forList3) {
            YxyHuodongResResultTea tea = null;
            sid = (String) map.get("sid");
            uid = (String) map.get("tid");
            list2 = tempRepository.findByTeaIdAndSchoolId(uid, sid);
            Integer count = 0;
            if (CollectionUtils.isNotEmpty(list2)) {
                for (int i = 0; i < list2.size(); i++) {
                    count += list2.get(i).getCount();
                    if (tea == null) {
                        tea = new YxyHuodongResResultTea();
                        tea.setSchoolId(sid);
                        tea.setTeaId(uid);
                        tea.setSchoolNick(list2.get(i).getSchoolNick());
                        tea.setTeaName(list2.get(i).getTeaName());
                        tea.setAreaIdCity(list2.get(i).getAreaIdCity());
                        tea.setAreaIdDistrict(list2.get(i).getAreaIdDistrict());
                        tea.setAreaIdProvince(list2.get(i).getAreaIdProvince());
                    }
                    type = list2.get(i).getType();
                    // 教案
                    if ("jl01".equals(type)) {
                        tea.setTeachingPlanCount(list2.get(i).getCount());
                        // 课件
                    } else if ("jl02".equals(type)) {
                        tea.setCoursewareCount(list2.get(i).getCount());
                        // 试题
                    } else if ("jl04".equals(type)) {
                        tea.setQuesCount(list2.get(i).getCount());
                        // 微课
                    } else if ("yx14".equals(type)) {
                        tea.setWeikeCount(list2.get(i).getCount());
                        // 素材
                    } else if ("jl06".equals(type)) {
                        tea.setMetterCount(list2.get(i).getCount());
                        // 其他
                    } else {
                        tea.setOtherCount(list2.get(i).getCount());
                    }

                }
            }
            tea.setResCount(count);
            list3.add(tea);
        }

        if (CollectionUtils.isNotEmpty(list3)) {
            List<YxyHuodongResResultTea> list4 = teaRepository.save(list3);
            LOGGER.info("保存成功tea：" + list4.size());
        }
        try {
            Thread.sleep(5000); // 1000 毫秒，也就是1秒.
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        String sql3 = "SELECT area_id_city AS ccode,area_id_province AS pcode,area_id_district AS dcode,school_id AS sid,school_nick AS sname,COUNT(id) AS teac,SUM(res_count) AS rescount,SUM(courseware_count) AS coursewarecount,SUM(metter_count) AS mettercount,SUM(other_count) AS othercount,SUM(ques_count) AS quescount,SUM(teaching_plan_count) AS teachingplancount,SUM(weike_count) AS weikecount FROM yxy_huodong.yxy_huodong_res_result_tea WHERE area_id_district='610203' GROUP BY school_id";
        List<Map<String, Object>> forList4 = template.queryForList(sql3);

        Long allCount = 1l;
        DecimalFormat df = new DecimalFormat("#0.00");
        ResponseEntity<Long> forEntity = null;
        Boolean flag = true;
        List<YxyHuodongResResultSchool> schools = new ArrayList<>();
        for (Map<String, Object> map : forList4) {
            YxyHuodongResResultSchool school = null;
            flag = true;
            if (school == null) {
                school = new YxyHuodongResResultSchool();
                school.setSchoolId(map.get("sid").toString());
                school.setSchoolNick(map.get("sname").toString());
                school.setAreaIdCity(map.get("ccode") != null ? map.get("ccode").toString() : "");
                school.setAreaIdDistrict(map.get("dcode") != null ? map.get("dcode").toString() : "");
                school.setAreaIdProvince(map.get("pcode") != null ? map.get("pcode").toString() : "");
            }
            school.setTeaCount(Integer.valueOf(map.get("teac").toString()));
            school.setResCount(Integer.valueOf(map.get("rescount").toString()));
            school.setTeachingPlanCount(Integer.valueOf(map.get("teachingplancount").toString()));
            school.setCoursewareCount(Integer.valueOf(map.get("coursewarecount").toString()));
            school.setQuesCount(Integer.valueOf(map.get("quescount").toString()));
            school.setWeikeCount(Integer.valueOf(map.get("weikecount").toString()));
            school.setMetterCount(Integer.valueOf(map.get("mettercount").toString()));
            school.setOtherCount(Integer.valueOf(map.get("othercount").toString()));

            try {
                // FIXME(修改路径)baseUrl
                forEntity = restTemplate.getForEntity(
                        "http://yuntest.91yunxiao.com/api_yx/comm/school/tea/count/" + map.get("sid").toString(),
                        Long.class);
                allCount = forEntity.getBody();
            } catch (RestClientException e) {
                flag = false;
                LOGGER.error("访问yx出错", e);
                e.printStackTrace();
            }
            if (flag && allCount > 0) {
                Double rate = Integer.valueOf(map.get("teac").toString()) * 1.00 / allCount;
                school.setTeaRate(Double.valueOf(df.format(rate * 100)));
            } else {
                school.setTeaRate(0.0);
            }
            schools.add(school);
        }
        if (CollectionUtils.isNotEmpty(schools)) {
            List<YxyHuodongResResultSchool> list4 = schoolRepository.save(schools);
            LOGGER.info("保存成功school：" + list4.size());
        }
    }

}
